<!DOCTYPE html>


  <html class="dark page-post">


<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="utf-8">
  
  <title>OOP之类与对象 | Poetry&#39;s Blog</title>

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  
    <meta name="keywords" content="JavaScript,面向对象,">
  

  <meta name="description" content="对象 对象的含义 所谓对象，就是一种无序的数据集合，由若干个“键值对”（key-value）构成">
<meta name="keywords" content="JavaScript,面向对象">
<meta property="og:type" content="article">
<meta property="og:title" content="OOP之类与对象">
<meta property="og:url" content="http://blog.poetries.top/2016/12/13/js-oop-and-class/index.html">
<meta property="og:site_name" content="Poetry&#39;s Blog">
<meta property="og:description" content="对象 对象的含义 所谓对象，就是一种无序的数据集合，由若干个“键值对”（key-value）构成">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2020-08-15T04:25:31.926Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="OOP之类与对象">
<meta name="twitter:description" content="对象 对象的含义 所谓对象，就是一种无序的数据集合，由若干个“键值对”（key-value）构成">

  

  
    <link rel="icon" href="/favicon.ico">
  

  <link href="/css/styles.css?v=c114cbeddx" rel="stylesheet">
<link href="/css/other.css?v=c114cbeddx" rel="stylesheet">


  
    <link rel="stylesheet" href="/css/personal-style.css">
  

  

  
  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "//hm.baidu.com/hm.js?40b1f89aa80f2527b3db779c6898c879";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>


  
  <script type="text/javascript">
	(function(){
	    var bp = document.createElement('script');
	    var curProtocol = window.location.protocol.split(':')[0];
	    if (curProtocol === 'https') {
	        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
	    }
	    else {
	        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
	    }
	    var s = document.getElementsByTagName("script")[0];
	    s.parentNode.insertBefore(bp, s);
	})();
  </script>



  
    <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <link rel="stylesheet" href="//cdn.bootcss.com/font-awesome/4.3.0/css/font-awesome.min.css">
  

  <!-- 聊天系统 -->
  
    
   <link type="text/css" rel="stylesheet" href="/renxi/default.css">
   <style>
      #modal {
        position: static !important;
      }
      .filter {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0;
        left: 0;
        background: #fe5757;
        animation: colorChange 30s ease-in-out infinite;
        animation-fill-mode: both;
        mix-blend-mode: overlay;
      }
  
      @keyframes colorChange {
        0%, 100% {
            opacity: 0;
        }
        50% {
            opacity: .9;
        }
      }
   </style>
</head>
</html>
<body>
  
  
    <span id="toolbox-mobile" class="toolbox-mobile">导航</span>
  

  <div class="post-header CENTER">
   
  <div class="toolbox">
    <a class="toolbox-entry" href="/">
      <span class="toolbox-entry-text">导航</span>
      <i class="icon-angle-down"></i>
      <i class="icon-home"></i>
    </a>
    <ul class="list-toolbox">
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/archives/"
            rel="noopener noreferrer"
            target="_self"
            >
            博客
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/categories/"
            rel="noopener noreferrer"
            target="_self"
            >
            分类
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/tags/"
            rel="noopener noreferrer"
            target="_self"
            >
            标签
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/search/"
            rel="noopener noreferrer"
            target="_self"
            >
            搜索
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/link/"
            rel="noopener noreferrer"
            target="_self"
            >
            友链
          </a>
        </li>
      
        <li class="item-toolbox">
          <a
            class="CIRCLE"
            href="/about/"
            rel="noopener noreferrer"
            target="_self"
            >
            关于
          </a>
        </li>
      
    </ul>
  </div>


</div>


  <div id="toc" class="toc-article">
    <strong class="toc-title">文章目录<i class="iconfont toc-title" style="display:inline-block;color:#87998d;width:20px;height:20px;">&#xf004b;</i></strong>
    <ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#对象"><span class="toc-text">对象</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#对象的含义"><span class="toc-text">对象的含义</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#对象的创建"><span class="toc-text">对象的创建</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#对象的基本操作"><span class="toc-text">对象的基本操作</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#Constructor属性"><span class="toc-text">Constructor属性</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#类的创建"><span class="toc-text">类的创建</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#this"><span class="toc-text">this</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#全局代码中的this"><span class="toc-text">全局代码中的this</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#普通的函数调用"><span class="toc-text">普通的函数调用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#在对象中使用"><span class="toc-text">在对象中使用</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#作为构造函数"><span class="toc-text">作为构造函数</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#多层嵌套的内部函数"><span class="toc-text">多层嵌套的内部函数</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#事件中的this"><span class="toc-text">事件中的this</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#使用apply和call改变this的指向"><span class="toc-text">使用apply和call改变this的指向</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#bind（）"><span class="toc-text">bind（）</span></a></li></ol></li></ol>
  </div>
  




<div class="content content-post CENTER">
   <!-- canvas 彩带 -->
<canvas id="evanyou" width="1302" height="678" style="position: fixed;width: 100%;height: 100%;top: 0;left:0;z-index:-1;"></canvas>

<article id="post-js-oop-and-class" class="article article-type-post" itemprop="blogPost">
  <header class="article-header" style="position:relative;">
    <h1 class="post-title">OOP之类与对象</h1>

    <div class="article-meta">
      <span>
        <i class="icon-calendar"></i>
        <span>2016.12.13</span>
      </span>

      
        <span class="article-author">
          <i class="icon-user"></i>
          <span>Poetry</span>
        </span>
      

      
  <span class="article-category">
    <i class="icon-list"></i>
    <a class="article-category-link" href="/categories/Front-End/">Front-End</a>
  </span>



      

      
      <i class="fa fa-eye"></i> 
        <span id="busuanzi_container_page_pv">
           &nbsp热度 <span id="busuanzi_value_page_pv">
           <i class="fa fa-spinner fa-spin"></i></span>℃
        </span>
      
      
       
          <span class="post-count">
            <i class="fa fa-file-word-o"></i>&nbsp
            <span>字数统计 1.4k字</span>
          </span>

          <span class="post-count">
            <i class="fa fa-columns"></i>&nbsp
            <span>阅读时长 5分</span>
          </span>
      
      
    </div>

    <i class="iconfont" id="toc-eye" style="display:inline-block;color:#b36619;position:absolute;top:0;right:0;cursor:pointer;
    font-size: 24px;">&#xe61c;</i>

  </header>

  <div class="article-content">
    
      <div id="container">
        <h4 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h4><hr>
<h5 id="对象的含义"><a href="#对象的含义" class="headerlink" title="对象的含义"></a>对象的含义</h5><ul>
<li><p>所谓对象，就是一种无序的数据集合，由若干个“键值对”（<code>key-value</code>）构成</p>
<a id="more"></a>
<h5 id="对象的创建"><a href="#对象的创建" class="headerlink" title="对象的创建"></a>对象的创建</h5></li>
<li><p>使用<code>new</code>运算符创建<code>Object</code></p>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> p = <span class="keyword">new</span> <span class="built_in">Object</span>();</span><br><span class="line">p.name = <span class="string">"Tony"</span>;</span><br></pre></td></tr></table></figure>
<ul>
<li>使用对象字面量的形式</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//对象字面量形式</span></span><br><span class="line"><span class="keyword">var</span> p =&#123;</span><br><span class="line">    name: <span class="string">"tony"</span>,</span><br><span class="line">    work: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">"working...."</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    _age: <span class="number">18</span>,</span><br><span class="line">    <span class="keyword">get</span> age()&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>._age;</span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="keyword">set</span> age(val)&#123;</span><br><span class="line">        <span class="keyword">if</span>( val &lt;<span class="number">0</span> || val &gt; <span class="number">150</span>)&#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">"invalid value"</span>);</span><br><span class="line">        &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">            <span class="keyword">this</span>._age = val;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(p.name);</span><br></pre></td></tr></table></figure>
<h5 id="对象的基本操作"><a href="#对象的基本操作" class="headerlink" title="对象的基本操作"></a>对象的基本操作</h5><ul>
<li>成员属性的添加</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">// Object.defineProperty()方法</span></span><br><span class="line"><span class="built_in">Object</span>.defineProperty(p, <span class="string">"age"</span>,&#123;<span class="attr">value</span>: <span class="number">18</span>, <span class="attr">writable</span>: <span class="literal">false</span>&#125;);</span><br><span class="line"><span class="comment">//Object.defineProperties()方法 添加多个属性</span></span><br><span class="line"><span class="built_in">Object</span>.defineProperties(p, &#123;</span><br><span class="line">    salary:&#123;</span><br><span class="line">        value: <span class="number">1000</span>,</span><br><span class="line">        writable: <span class="literal">false</span></span><br><span class="line">    &#125;,</span><br><span class="line">    gender:&#123;</span><br><span class="line">        value: <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<ul>
<li><p>成员的遍历</p>
<ul>
<li>使用 <code>for..in</code>语句</li>
<li><code>Object.keys()</code>方法 返回一个包含对象键名的字符串数组</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> o =&#123;&#125;;</span><br><span class="line">o.name = <span class="string">"jack"</span>;</span><br><span class="line">o.age = <span class="number">20</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i <span class="keyword">in</span> o)&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(o[i]);</span><br><span class="line">&#125; <span class="comment">// jack, 20</span></span><br><span class="line"><span class="built_in">Object</span>.keys(o); <span class="comment">// ["name", "age"]</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p>检查对象是否有某个属性</p>
<ul>
<li><code>in</code> 操作符</li>
<li><code>Object.hasOwnProperty()</code>方法</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;<span class="attr">name</span>: <span class="string">"mariya"</span>&#125;</span><br><span class="line"><span class="string">"name"</span> <span class="keyword">in</span> o; <span class="comment">// true</span></span><br><span class="line">o.hasOwnProperty(<span class="string">"name"</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<ul>
<li>得到对象的属性特性描述 <code>Object.getOwnPropertyDescriptor(obj,property)</code></li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="built_in">Object</span>.getOwnPropertyDescriptor(o, <span class="string">"name"</span>);</span><br><span class="line"><span class="comment">//Object &#123;</span></span><br><span class="line"><span class="comment">//    value: "mariya", writable: true, enumerable: true, configurable: true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>删除属性<ul>
<li><code>delete</code>运算符,但有些对象的属性是删除不了的</li>
</ul>
</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">delete</span> o.name; <span class="comment">//true</span></span><br><span class="line">o.name;  <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
<h5 id="Constructor属性"><a href="#Constructor属性" class="headerlink" title="Constructor属性"></a>Constructor属性</h5><ul>
<li><code>constructor</code>始终指向创建当前对象的构造函数</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [];</span><br><span class="line"><span class="built_in">console</span>.log(arr.constructor === <span class="built_in">Array</span>); <span class="comment">// true</span></span><br><span class="line"><span class="keyword">var</span> Foo = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;&#125;;</span><br><span class="line"><span class="built_in">console</span>.log(Foo.constructor === <span class="built_in">Function</span>); <span class="comment">// true</span></span><br><span class="line"><span class="comment">// 由构造函数实例化一个obj对象</span></span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> Foo();</span><br><span class="line"><span class="built_in">console</span>.log(obj.constructor === Foo); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">console</span>.log(obj.constructor.constructor === <span class="built_in">Function</span>); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>
<ul>
<li>每个函数都有一个默认的属性<code>prototype</code>，而这个<code>prototype</code>的<code>constructor</code>默认指向这个函数</li>
</ul>
<h4 id="类的创建"><a href="#类的创建" class="headerlink" title="类的创建"></a>类的创建</h4><hr>
<ul>
<li><p>虽然<code>js</code>是门基于对象的语言，但是没有类这一概念的，虽然保留了<code>class</code>的关键字，但在<code>ES6</code>之前是无法使用的。所以，可以用构造函数模拟类的创建，也就是伪类。</p>
</li>
<li><p>所谓”构造函数”，其实就是一个普通函数，但是内部使用了<code>this</code>变量。对构造函数使用<code>new</code>运算符，就能生成实例，并且<code>this</code>变量会绑定在实例对象上</p>
</li>
<li>每一个构造函数都有一个<code>prototype</code>属性，指向另一个对象。这个对象的所有属性和方法，都会被构造函数的实例继承</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="comment">//构造函数模式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Person</span>(<span class="params">age, name</span>)</span>&#123; <span class="comment">//Class</span></span><br><span class="line">    <span class="keyword">this</span>.age = age;</span><br><span class="line">    <span class="keyword">this</span>.name = name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//将公共的属性或方法放在prototype属性上</span></span><br><span class="line">Person.prototype.headCount = <span class="number">1</span>;</span><br><span class="line"><span class="comment">//创建实例对象</span></span><br><span class="line"><span class="keyword">var</span> p = <span class="keyword">new</span> Person(<span class="number">19</span>, <span class="string">'johnsom'</span>);</span><br><span class="line"><span class="keyword">var</span> p1 = <span class="keyword">new</span> Person(<span class="number">20</span>, <span class="string">'allen'</span>);</span><br></pre></td></tr></table></figure>
<h4 id="this"><a href="#this" class="headerlink" title="this"></a>this</h4><hr>
<ul>
<li><code>this</code>表示当前对象，如果在全局作用范围内使用<code>this</code>，则指代当前页面对象<code>window</code>； 如果在函数中使用<code>this</code>，则<code>this</code>指代什么是根据运行时此函数在什么对象上被调用。 我们还可以使用<code>apply</code>和<code>call</code>两个全局方法来改变函数中<code>this</code>的具体指向</li>
</ul>
<h5 id="全局代码中的this"><a href="#全局代码中的this" class="headerlink" title="全局代码中的this"></a>全局代码中的this</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="keyword">this</span> === <span class="built_in">window</span>); <span class="comment">//true 全局范围内使用this指向window对象</span></span><br></pre></td></tr></table></figure>
<h5 id="普通的函数调用"><a href="#普通的函数调用" class="headerlink" title="普通的函数调用"></a>普通的函数调用</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line"><span class="keyword">this</span>.name = <span class="string">"tony"</span>; <span class="comment">// this在运行时指向window对象,在严格模式下则是undefined</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="在对象中使用"><a href="#在对象中使用" class="headerlink" title="在对象中使用"></a>在对象中使用</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">    name: <span class="string">"tony"</span>,</span><br><span class="line">    print: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">this</span>.name);  <span class="comment">//this指向对象o，但是可以改变其指向</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>
<h5 id="作为构造函数"><a href="#作为构造函数" class="headerlink" title="作为构造函数"></a>作为构造函数</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">new</span> F(); <span class="comment">// 函数内部的this指向新创建的对象。</span></span><br></pre></td></tr></table></figure>
<h5 id="多层嵌套的内部函数"><a href="#多层嵌套的内部函数" class="headerlink" title="多层嵌套的内部函数"></a>多层嵌套的内部函数</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> name = <span class="string">"global"</span>;</span><br><span class="line"><span class="keyword">var</span> person = &#123;</span><br><span class="line">    name : <span class="string">"person"</span>,</span><br><span class="line">    hello : <span class="function"><span class="keyword">function</span>(<span class="params">sth</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> sayhello = <span class="function"><span class="keyword">function</span>(<span class="params">sth</span>) </span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="keyword">this</span>.name + <span class="string">" says "</span> + sth);</span><br><span class="line">        &#125;;</span><br><span class="line">        sayhello(sth);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">person.hello(<span class="string">"hello world"</span>);<span class="comment">//global says hello world</span></span><br></pre></td></tr></table></figure>
<ul>
<li>在内部函数中，<code>this</code>没有按预想的绑定到外层函数对象上，而是绑定到了全局对象。这里普遍被认为是<code>JavaScript</code>语言的设计错误，因为没有人想让内部函数中的<code>this</code>指向全局对象。一般的处理方式是将<code>this</code>作为变量保存下来，一般约定为<code>that</code>或者<code>self</code>：</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> name = <span class="string">"global"</span>;</span><br><span class="line"><span class="keyword">var</span> person = &#123;</span><br><span class="line">    name : <span class="string">"person"</span>,</span><br><span class="line">    hello : <span class="function"><span class="keyword">function</span>(<span class="params">sth</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> that = <span class="keyword">this</span>;</span><br><span class="line">        <span class="keyword">var</span> sayhello = <span class="function"><span class="keyword">function</span>(<span class="params">sth</span>) </span>&#123;</span><br><span class="line">            <span class="built_in">console</span>.log(that.name + <span class="string">" says "</span> + sth);</span><br><span class="line">        &#125;;</span><br><span class="line">        sayhello(sth);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">person.hello(<span class="string">"hello world"</span>);<span class="comment">//person says hello world</span></span><br></pre></td></tr></table></figure>
<h5 id="事件中的this"><a href="#事件中的this" class="headerlink" title="事件中的this"></a>事件中的this</h5><figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> ele = <span class="built_in">document</span>.getElementById(<span class="string">"id"</span>);</span><br><span class="line">ele.addEventListener(<span class="string">'click'</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span>);  <span class="comment">//this指向dom元素</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<h5 id="使用apply和call改变this的指向"><a href="#使用apply和call改变this的指向" class="headerlink" title="使用apply和call改变this的指向"></a>使用apply和call改变this的指向</h5><ul>
<li><code>apply</code>和<code>call</code>类似，只是后面的参数是通过一个数组传入，而不是分开传入。两者都是将某个函数绑定到某个具体对象上使用，自然此时的<code>this</code>会被显式的设置为第一个参数。两者的方法定义：</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">call( thisArg [，arg1，arg2，… ] );  <span class="comment">// 参数列表，arg1，arg2，...</span></span><br><span class="line">apply(thisArg [，argArray] );     <span class="comment">// 参数数组，argArray</span></span><br></pre></td></tr></table></figure>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line"><span class="keyword">var</span> name = <span class="string">'global'</span>;</span><br><span class="line"><span class="keyword">var</span> o = &#123;</span><br><span class="line">    name: <span class="string">'job'</span>,</span><br><span class="line">    getName: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="keyword">this</span>.name);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;;</span><br><span class="line">o.getName(); <span class="comment">// job</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//用call或apply改变函数中this的指向</span></span><br><span class="line">o.getName.call(<span class="keyword">this</span>); <span class="comment">// global</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p><strong>简单的总结：</strong></p>
<ul>
<li>当函数作为对象的方法调用时，<code>this</code>指向该对象。</li>
<li>构造函数中的<code>this</code>指向新创建的对象</li>
<li>嵌套函数中的<code>this</code>不会继承上层函数的<code>this</code>，如果需要，可以用一个变量保存上层函数的<code>this</code></li>
</ul>
</li>
</ul>
<h5 id="bind（）"><a href="#bind（）" class="headerlink" title="bind（）"></a>bind（）</h5><ul>
<li>该方法创建一个新函数，称为绑定函数，绑定函数会以创建它时传入<code>bind</code>方法的第一个参数作为<code>this</code>，传入<code>bind</code>方法的第二个以及以后的参数加上绑定函数运行时本身的参数按照顺序作为原函数的参数来调用原函数.</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="code"><pre><span class="line">$(<span class="string">"#ele"</span>).click(person.hello.bind(person));</span><br><span class="line"><span class="comment">//相应元素被点击时，输出person says hello world</span></span><br></pre></td></tr></table></figure>
      </div>
    
  </div>

</article>

<button class="assist-btn2 circle" id="assist_btn2" title="点亮屏幕" style="left: 27px; top: 152px;">
  <i class="iconfont" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>
<button class="assist-btn1 circle" id="assist_btn1" title="关闭屏幕亮度" style="left: 27px; top: 152px;">
  <i class="iconfont toc-title" style="display:inline-block;color:red;width:20px;height:20px;">&#xe61d;</i>
</button>


<script src="//cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script>	

<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
<script>
  const btw = new BTWPlugin();
  btw.init({
    id: "container",
    blogId: "22699-1592137983091-414",
    name: "前端进阶之旅",
    qrcode: "https://poetries1.gitee.io/img-repo/2020/06/qrcode.jpg",
    keyword: "3a3b3c",
  });
</script>

<script type="text/javascript">

// white theme
var body = {color: "#555", background: "#000"};
var a_tag = {color: "#222"};
var header = { background: "#222"};
var logo_line_i = {background: "#222"};
// var post_code = {background: "#eee", color: "#222"};

function switch_theme() {
 $("body").css(body);
 $("a:not('.links-of-author-item a, .site-state-item a, .site-state-posts a, .feed-link a, .motion-element a, .post-tags a, .show-commit-cls a, #donate_board a')").css(a_tag);
 $(".header, .footer").css(header);
 $(".logo-line-before i, .logo-line-after i").css(logo_line_i);
 //$(".post code").css(post_code);
 $("#idhyt-surprise-ball #idhyt-surprise-ball-animation .drag").css(a_tag);
 $(".post-title-link, .posts-expand .post-meta, .post-comments-count, .disqus-comment-count, .post-category a, .post-nav-next a, .post-nav-item a").css(a_tag);
 
 // $("code").css({color: '#c5c8c6', background: '#1d1f21'});
 //$("#assist_btn1").hide(1500);
}

$(function () {
$("#assist_btn2").css("display","none");
 $("#assist_btn1").click(function() {
     switch_theme();
$("div#toc.toc-article").css({
 "background":"#eaeaea",
 "opacity":1
});
$(".toc-article ol").show();
$("#toc.toc-article .toc-title").css("color","#a98602");
$("#assist_btn1").css("display","none");
$("#assist_btn2").css("display","block");
 });
$("#assist_btn2").click(function() {
$("#assist_btn2").css("display","none");
$("#assist_btn1").css("display","block");
$("body").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
     $(".header, .footer").css("background","url(http://www.miaov.com/static/ie/images/news/bg.png)")
$(".toc-article ol").toggle(1000);
 });
});


//背景随机

var Y, O, E, L, B, C, T, z, N, S, A, I;
!function() {
var e = function() {
for (O.clearRect(0, 0, L, B), T = [{
x: 0,
y: .7 * B + C
}, {
x: 0,
y: .7 * B - C
}]; T[1].x < L + C;) t(T[0], T[1])
}, t = function(e, t) {
O.beginPath(), O.moveTo(e.x, e.y), O.lineTo(t.x, t.y);
var n = t.x + (2 * I() - .25) * C,
 r = a(t.y);
O.lineTo(n, r), O.closePath(), N -= S / -50, O.fillStyle = "#" + (127 * A(N) + 128 << 16 | 127 * A(N + S / 3) + 128 << 8 | 127 * A(N + S / 3 * 2) + 128).toString(16), O.fill(), T[0] = T[1], T[1] = {
 x: n,
 y: r
}
}, a = function n(e) {
var t = e + (2 * I() - 1.1) * C;
return t > B || t < 0 ? n(e) : t
};
Y = document.getElementById("evanyou"), O = Y.getContext("2d"), E = window.devicePixelRatio || 1, L = window.innerWidth, B = window.innerHeight, C = 90, z = Math, N = 0, S = 2 * z.PI, A = z.cos, I = z.random, Y.width = L * E, Y.height = B * E, O.scale(E, E), O.globalAlpha = .6, document.onclick = e, document.ontouchstart = e, e()
}()

   
$("#toc-eye").click(function(){
$("#toc.toc-article").toggle(1000);
});

</script>


   
  <div class="text-center donation">
    <div class="inner-donation">
      <span class="btn-donation">支持一下</span>
      <div class="donation-body">
        <div class="tip text-center">扫一扫，支持poetries</div>
        <ul>
        
          <li class="item">
            
              <span>微信扫一扫</span>
            
            <img src="/images/weixin.jpg" alt="">
          </li>
        
          <li class="item">
            
              <span>支付宝扫一扫</span>
            
            <img src="/images/zhifubao.jpg" alt="">
          </li>
        
        </ul>
      </div>
    </div>
  </div>


   
  <div class="box-prev-next clearfix">
    <a class="show pull-left" href="/2016/12/13/js-oop/">
        <i class="icon icon-angle-left"></i>
    </a>
    <a class="show pull-right" href="/2016/12/13/js-inherit/">
        <i class="icon icon-angle-right"></i>
    </a>
  </div>




</div>


  <a id="backTop" class="back-top">
    <i class="icon-angle-up"></i>
  </a>




  <div class="modal" id="modal">
  <span id="cover" class="cover hide"></span>
  <div id="modal-dialog" class="modal-dialog hide-dialog">
    <div class="modal-header">
      <span id="close" class="btn-close">关闭</span>
    </div>
    <hr>
    <div class="modal-body">
      <ul class="list-toolbox">
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/archives/"
              rel="noopener noreferrer"
              target="_self"
              >
              博客
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/categories/"
              rel="noopener noreferrer"
              target="_self"
              >
              分类
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/tags/"
              rel="noopener noreferrer"
              target="_self"
              >
              标签
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/search/"
              rel="noopener noreferrer"
              target="_self"
              >
              搜索
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/link/"
              rel="noopener noreferrer"
              target="_self"
              >
              友链
            </a>
          </li>
        
          <li class="item-toolbox">
            <a
              class="CIRCLE"
              href="/about/"
              rel="noopener noreferrer"
              target="_self"
              >
              关于
            </a>
          </li>
        
      </ul>

    </div>
  </div>
</div>



  
      <div class="fexo-comments comments-post">
    

    

    
    

    

    
    

    

<!-- Gitalk评论插件通用代码 -->
<div id="gitalk-container"></div>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.css">
<script src="https://cdn.jsdelivr.net/npm/gitalk@1/dist/gitalk.min.js"></script>
<script>
const gitalk = new Gitalk({
  clientID: '5567a2c4abb858009d96',
  clientSecret: 'b9039ec056cf5c2346b3cdb63308a28c163f91e5',
  repo: 'poetries.github.io',
  owner: 'poetries',
  // 在这里设置一下截取前50个字符串, 这是因为 github 对 label 的长度有了要求, 如果超过
  // 50个字符串则会报错.
  // id: location.pathname.split('/').pop().substring(0, 49),
  id: location.pathname,
  admin: ['poetries'],
  // facebook-like distraction free mode
  distractionFreeMode: false
})
gitalk.render('gitalk-container')
</script>
<!-- Gitalk代码结束 -->



  </div>

  

  <script type="text/javascript">
  function loadScript(url, callback) {
    var script = document.createElement('script')
    script.type = 'text/javascript';

    if (script.readyState) { //IE
      script.onreadystatechange = function() {
        if (script.readyState == 'loaded' ||
          script.readyState == 'complete') {
          script.onreadystatechange = null;
          callback();
        }
      };
    } else { //Others
      script.onload = function() {
        callback();
      };
    }

    script.src = url;
    document.getElementsByTagName('head')[0].appendChild(script);
  }

  window.onload = function() {
    loadScript('/js/bundle.js?235683', function() {
      // load success
    });
  }
</script>


  <!-- 页面点击小红心 -->
  <script type="text/javascript" src="/js/clicklove.js"></script>
 
  
</body>
</html>
